//
//  BlueToothManager.swift
//  jiahui
//
//  Created by 3tee on 2024/12/23.
//

import Foundation
import CoreBluetooth

class BlueToothManager :NSObject{
    var peripheral: CBPeripheral?
    var centralManager: CBCentralManager!
    var peripheralNameToConnect: String?
    override init() {
        super.init()
        //peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
        centralManager = CBCentralManager(delegate: self, queue: nil)
        peripheralNameToConnect = "capybara"
    }
    
}

extension BlueToothManager: CBCentralManagerDelegate,CBPeripheralDelegate{
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state{
        case .poweredOn:
            print("蓝牙已经打开")
            //扫描外包设备
            centralManager.scanForPeripherals(withServices: nil, options: nil)
        case .poweredOff:
            print("poweredOff")
        case .resetting:
            print("resetting")
        case .unauthorized:
            print("unauthorized")
        case .unknown:
            print("unknown")
        case .unsupported:
            print("unsupported")
        @unknown default:
            break
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("发现外围设备 \(peripheral.name) ")
        if let name = peripheral.name, name == peripheralNameToConnect {
            // 找到了要连接的设备
            self.peripheral = peripheral
            self.peripheral?.delegate = self
            self.centralManager.connect(peripheral, options: nil) // 连接设备
        }
    }
    
    
    // 连接成功的回调
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Connected to \(peripheral.name ?? "")")
        // 这里可以设置服务、特性等进一步操作
        peripheral.discoverServices(nil)
        self.centralManager.stopScan() // 停止扫描

    }
    
    
    
    // 连接失败的回调
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("Failed to connect to \(peripheral.name ?? ""): \(error?.localizedDescription ?? "")")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: (any Error)?) {
        if let services = peripheral.services {
            for service in services {
                print("service: \(service.uuid)")
                peripheral.discoverCharacteristics(nil, for: service)
            }
        }
    }
    /*
     characteristic: BDA65297-D43B-4E22-B424-012345678900
     characteristic: BDA65297-D43B-4E22-B424-012345678901
     characteristic: 982A921C-C083-47EA-B6BE-F2D637969D91
     characteristic: 5AA977EF-AA32-4E4D-8F45-E381DC479EEA
    */
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: (any Error)?) {
        for inst in service.characteristics ?? [] {
            print("characteristic: \(inst.uuid)")
            peripheral.readValue(for: inst)
           
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: (any Error)?) {
        if let data = characteristic.value {
            let stringValue = String(data: data, encoding: .utf8) ?? "nil"
            print("value: \(stringValue)")
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: (any Error)?) {
        if error == nil {
                print("Successfully wrote value to characteristic \(characteristic.uuid)")
            } else {
                print("Error writing value to characteristic \(characteristic.uuid): \(String(describing: error?.localizedDescription))")
            }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: (any Error)?) {
        if error == nil {
               print("Successfully wrote value to descriptor \(descriptor.uuid)")
           } else {
               print("Error writing value to descriptor \(descriptor.uuid): \(String(describing: error?.localizedDescription))")
           }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
        for service in invalidatedServices {
            print("service: \(service.uuid)")
        }
    }
    
}
